/**
 * Storage Service for handling offline map data
 * Provides methods for saving, loading, and editing map tracks
 */

// Save track data to local storage
export const saveTrackData = (trackData) => {
  // Create a unique ID for the track if not exists
  if (!trackData.id) {
    trackData.id = `track_${Date.now()}`;
  }

  // Get existing saved tracks
  const savedTracks = getSavedTracks();

  // Add the new track
  savedTracks.push(trackData);

  // Save back to storage
  uni.setStorageSync("saved_tracks", JSON.stringify(savedTracks));

  return trackData.id;
};

// Get all saved tracks
export const getSavedTracks = () => {
  try {
    const tracksData = uni.getStorageSync("saved_tracks");
    return tracksData ? JSON.parse(tracksData) : [];
  } catch (e) {
    console.error("Error getting saved tracks:", e);
    return [];
  }
};

// Get a specific track by ID
export const getTrackById = (trackId) => {
  const savedTracks = getSavedTracks();
  return savedTracks.find((track) => track.id === trackId);
};

// Delete a track by ID
export const deleteTrack = (trackId) => {
  let savedTracks = getSavedTracks();
  savedTracks = savedTracks.filter((track) => track.id !== trackId);
  uni.setStorageSync("saved_tracks", JSON.stringify(savedTracks));
};

// Update a track (e.g., after moving points)
export const updateTrack = (trackId, updatedData) => {
  let savedTracks = getSavedTracks();
  const index = savedTracks.findIndex((track) => track.id === trackId);

  if (index !== -1) {
    // Merge the updated data with existing track
    savedTracks[index] = {
      ...savedTracks[index],
      ...updatedData,
      lastModified: Date.now(),
    };

    // Save back to storage
    uni.setStorageSync("saved_tracks", JSON.stringify(savedTracks));
    return true;
  }

  return false;
};

// Save the current map area for offline use
export const saveMapArea = (region) => {
  try {
    // Store the map region data including center point and zoom level
    uni.setStorageSync(
      "offline_map_area",
      JSON.stringify({
        latitude: region.latitude,
        longitude: region.longitude,
        scale: region.scale,
        timestamp: Date.now(),
      })
    );
    return true;
  } catch (e) {
    console.error("Error saving map area:", e);
    return false;
  }
};

// Get the saved map area
export const getSavedMapArea = () => {
  try {
    const mapArea = uni.getStorageSync("offline_map_area");
    return mapArea ? JSON.parse(mapArea) : null;
  } catch (e) {
    console.error("Error getting saved map area:", e);
    return null;
  }
};

// Check if the app is in offline mode
export const isOfflineMode = () => {
  try {
    return uni.getStorageSync("offline_mode") === "true";
  } catch (e) {
    return false;
  }
};

// Set offline mode
export const setOfflineMode = (isOffline) => {
  uni.setStorageSync("offline_mode", isOffline ? "true" : "false");
};

// Get all offline maps
export const getOfflineMaps = () => {
  try {
    const mapsData = uni.getStorageSync("offline_maps");
    return mapsData ? JSON.parse(mapsData) : [];
  } catch (e) {
    console.error("Error getting offline maps:", e);
    return [];
  }
};

// Save a new offline map
export const saveOfflineMap = (mapData) => {
  try {
    // Create a unique ID for the map if not exists
    if (!mapData.id) {
      mapData.id = `map_${Date.now()}`;
    }

    // Get existing offline maps
    const offlineMaps = getOfflineMaps();

    // Add the new map
    offlineMaps.push(mapData);

    // Save back to storage
    uni.setStorageSync("offline_maps", JSON.stringify(offlineMaps));

    return mapData.id;
  } catch (e) {
    console.error("Error saving offline map:", e);
    return null;
  }
};

// Delete an offline map
export const deleteOfflineMap = (mapId) => {
  try {
    let offlineMaps = getOfflineMaps();
    offlineMaps = offlineMaps.filter((map) => map.id !== mapId);
    uni.setStorageSync("offline_maps", JSON.stringify(offlineMaps));
    return true;
  } catch (e) {
    console.error("Error deleting offline map:", e);
    return false;
  }
};

// Get a specific offline map by ID
export const getOfflineMapById = (mapId) => {
  const offlineMaps = getOfflineMaps();
  return offlineMaps.find((map) => map.id === mapId);
};
